<?php

require_once('../engine/engine.php');
require_once('../dbo/projects.php');
/**#@-*/

init_page(LOAD_TAB);

if (get_user_level() != USER_LEVEL_ADMIN)
{
    debug_write_log(DEBUG_NOTICE, 'User must have admin rights to be allowed.');
    exit;
}

// XML file is submitted

$ok = null;
if (try_request('submitted') == 'mainform')
{
    debug_write_log(DEBUG_NOTICE, 'Data are submitted.');

    $error = NULL;

    $id = isset($_FILES['xmlfile'])
        ? project_import($_FILES['xmlfile'], $error, true)
        : 0;

    if ($id == 0 && ustrlen($error) != 0)
    {
	send_http_error($error);
    }
    else
    {
        /**
         * jQuery Form Plugin uses "success" callback function in both cases - success and failure
         * (see https://github.com/malsup/form/issues/107 for details).
         * It makes impossible to distinguish successful response from error messages.
         * To make the difference a successful response is prefixed with "OK ".
         * For the same reasons a workaround function "importSuccess2" is appeared (see its code below).
         */
        header('HTTP/1.0 200 OK');
	echo('OK');
    }
    exit;
}
else
{
    debug_write_log(DEBUG_NOTICE, 'Data are being requested.');
}

// local JS functions

$resTitle = get_js_resource(RES_ERROR_ID);
$resOK    = get_js_resource(RES_OK_ID);

$xml = <<<JQUERY
<script>

function importSuccess ()
{
	window.open("index.php?set_template=1", "_parent");
}

function importError (XMLHttpRequest)
{
    jqAlert("{$resTitle}", XMLHttpRequest.responseText, "{$resOK}");
}

function importSuccess2 (data)
{
    if (data.substr(0,2) == "OK")  // success
    {
        importSuccess();
    }
    else    // error
    {
        jqAlert("{$resTitle}", data, "{$resOK}");
    }
}

</script>
JQUERY;

// generate page

$xml .= '<form name="mainform" action="project_template.php" upload="' . (ATTACHMENTS_MAXSIZE * 1024) . '" success="importSuccess2" error="importError">'
      . '<group>'
      . '<control name="xmlfile" required="' . get_html_resource(RES_REQUIRED3_ID) . '">'
      . '<label>' . get_html_resource(RES_TEMPLATE_ID) . '</label>'
      . '<filebox/>';
$xml .= '</control>';
$xml .= '</group>';
$xml .= '<button default="true">' . get_html_resource(RES_OK_ID) . '</button>';
if (is_file(UPLOAD_PATH . "/project_template.xml"))
    $xml .= '<note>' . 'A project template is already set. By uploading a new template you are overwritting the existing one.' . '</note>';

$xml .= '</form>';

echo(xml2html($xml));

?>
